import {Component, OnInit} from '@angular/core';
import {FetchService} from "../../../../core/net/fetch.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import * as moment from "moment";
import * as _ from 'lodash';
import {NzMessageService} from "ng-zorro-antd";
import { HttpClient } from '@angular/common/http';

const MonthPropsHash = new Map([
    ['1月', 'janMwo'],
    ['2月', 'febMwo'],
    ['3月', 'marMwo'],
    ['4月', 'aprMwo'],
    ['5月', 'mayMwo'],
    ['6月', 'junMwo'],
    ['7月', 'julMwo'],
    ['8月', 'augMwo'],
    ['9月', 'sepMwo'],
    ['10月', 'octMwo'],
    ['11月', 'novMwo'],
    ['12月', 'decMwo']
]);

@Component({
    selector: 'app-wt-industrial',
    templateUrl: './wt-industrial.component.html',
    styleUrls: ['./wt-industrial.component.scss', '../water-takes-report.component.scss']
})
export class WtIndustrialComponent implements OnInit {
    year = moment().valueOf();
    searchForm: FormGroup;
    monthlyTableData = [];
    pageNum: number = 1;
    pageSize: number = 10;
    total: number;
    basicOpts: any = {
        title: {
            text: "",
            x: "center",
            textStyle: {
                color: "#777",
                fontSize: 16
            }
        },
        color: ['#3398DB', '#ddb00a'],
        grid: {
            top: '10%',
            left: '8%',
            right: '8%',
            bottom: '12%',
            containLabel: true
        },
        tooltip: {
            trigger: "axis"
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: MonthPropsHash.keys(),
            axisLabel: {
                interval: 0
            }
        },
        yAxis: {
            type: "value"
        }
    };
    customOpts: any = {};
    progressModalShow: boolean = false;
    progressData = [];
    reportFinished = 0;
    reportUnfinished = 0;
    reportPercentage = 0;
    constructor(private fetchService: FetchService,
                private fb: FormBuilder,
                private http: HttpClient,
                private message: NzMessageService) {
    }

    ngOnInit() {
        this.searchForm = this.fb.group({
            year: [null],
            name: [null]
        });
        this.searchForm.patchValue({
            year: moment().valueOf()
        });
        this.queryInfo();
        this.getProgressData();
    }
    getProgressData(): void {
        this.fetchService.get<any>('muw/submit/querySubmitInd').subscribe(res => {
            if (res) {
                const group = _.groupBy(res, 'statu');
                this.reportFinished = group['2'] ? group['2'].length : 0;
                this.reportUnfinished = group['1'] ? group['1'].length : 0;
                this.reportPercentage = res.length === 0 ? 0 : Math.round(this.reportFinished / res.length * 100);
                res.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                });
                this.progressData = _.sortBy(res, o => {
                    return o.statu;
                });
            }
        });
    }
    openProgressModal(): void {
        this.progressModalShow = true;
    }
    closeProgressModal() {
        this.progressModalShow = false;
    }
    export(): void {
        const params = {
            year: moment(this.searchForm.value.year).year(),
            name: this.searchForm.value.name,
        };
        this.fetchService.export('muw/wrsMuwIndData/export', params).subscribe((res: any) => {
            const blob = new Blob([res], {type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8'});
            const elink = document.createElement('a');

            elink.download = `工业取水.xlsx`;
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        });
    }

    print(): void {
    }

    queryInfo(reset: boolean = false): void {
        if (reset) {
            this.pageNum = 1;
        }
        const params = {
            year: moment(this.searchForm.value.year).year(),
            name: this.searchForm.value.name,
            pageNum: this.pageNum,
            pageSize: this.pageSize
        };
        this.fetchService.post('muw/wrsMuwIndData/list', params).subscribe(res => {
            res['list'].forEach(item => {
                item['total'] = _.reduce(item, (total, val, key: string) => {
                    total += _.endsWith(key, 'Mwo') ? parseFloat(val || '0') : 0;
                    return total;
                }, 0);
            });
            this.monthlyTableData = res['list'];
            this.total = res['total'];
            this.selectedRow(this.monthlyTableData[0]);
        });
    }

    selectedRow(data): void {
        const seriesData = [];
        MonthPropsHash.forEach(val => {
            seriesData.push(data[val]);
        });
        this.customOpts = {
            title: {
                text: `${data.trIndName}月用水量`
            },
            yAxis: {
                name: '月用水量(万m³)'
            },
            series: [
                {
                    name: '用水量',
                    type: 'line',
                    data: seriesData
                }
            ]
        };
    }
    broadcast() {
        this.message.success('通知消息已下发到管理处');
    }
}
